<!-- Created by jack on 2022/3/17 - 09:42 -->
<style scoped lang="less">
.main{
  position: absolute;
  color: v-bind(color);
  font-size: 16px;
  top: v-bind(top);
  left: v-bind(left);
  z-index: 20001;
  &__popup-top{
    border-radius: 4px;
    background: v-bind(background);
    padding: 2px 10px;
    position: relative;
    &::after{
      bottom: -16px;
      position: absolute;
      content:'';
      border: 8px solid v-bind(background);
      border-left-color: transparent;
      border-right-color: transparent;
      border-bottom-color: transparent;
      left: 50%;
      transform: translateX(-50%);
    }
  }
}
.fade-enter-active, .fade-leave-active{
  transition: opacity v-bind(delayTime);
}
.fade-enter, .fade-leave-to{
  opacity: 0;
}
</style>

<template>
  <transition name="fade">
    <div class="main" ref="toolTip" v-show="show">
      <div class="main__popup" :class="`main__popup-${arrowPosition}`">{{ value }}</div>
    </div>
  </transition>
</template>

<script lang="ts" setup>
import {computed, nextTick, onMounted, onUnmounted, ref, watch} from "vue";
import {getDomPosition} from "@/helper";

const props = defineProps({
  el:{ type:HTMLElement ,default: ''},
  position:{ type:String}, // left top right bottom
  backgroundColor:{ type:String}, // tooltip background color
  textColor:{ type:String}, // tooltip background color
  showDelay:{ type:Number}, // delay show time, unit ms
  value:{ type:String }, // show text
  gap:{ type:[Number,String] }, // gap
})


const delayTime = computed( _ => props?.showDelay && props?.showDelay < 300 ? `300ms` : `${props?.showDelay || 300}ms`) // get delayTime
const arrowPosition = computed( _=> props?.position && ['left','right','top','bottom'].includes(props?.position) ? props.position : 'top') // check has position,
const background = computed(_ => props?.backgroundColor?? 'rgba(211,202,202,0.5)' )
const color = computed(_ => props?.textColor?? 'rgba(49,48,48,0.63)' )
const gapLength = computed(_ => props?.gap || 40 )
const domPosition = computed(_ => getDomPosition( props?.el,false)  )
//todo 目前只支持top
let show = ref(false)
const toolTip = ref()
let left = ref('')
const top = computed(_ => (domPosition.value?.top - gapLength.value) + 'px')


/** 挂在监听事件 */
onMounted( () => {
  if(props.el){
    props.el.addEventListener('mousemove', (event:MouseEvent) => {
      show.value = true
    })
    props.el.addEventListener('mouseout', (event) => {
      show.value = false
    })
  }
})
watch(show, (value) => {
  if(value){
    nextTick(() => {
      const domPosition = getDomPosition( props?.el,false)
      left.value = domPosition.left + ( domPosition.width - getDomPosition(toolTip.value).width )/ 2 + 'px'
    })
  }
})
onUnmounted(() => {
  if(props.el){
    props.el.removeEventListener('mousemove',() => {})
    props.el.removeEventListener('mouseout',() => {})
  }
})
</script>
